package com.ruoyi.workflow.util;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.workflow.exception.FlowModelException;
import com.ruoyi.workflow.validation.EndEventValidator;
import com.ruoyi.workflow.validation.ExclusiveGatewayValidator;
import com.ruoyi.workflow.validation.MultiInstanceLoopCharacteristicsValidator;
import com.ruoyi.workflow.validation.UserTaskValidator;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.camunda.bpm.model.xml.validation.ModelElementValidator;
import org.camunda.bpm.model.xml.validation.ValidationResult;
import org.camunda.bpm.model.xml.validation.ValidationResults;

import java.util.*;

/**
 * 模型元素校验工具类
 *
 * @author TD
 * @version 1.0
 * @date 2024/1/15
 */
public class ModelElementValidateUtils {

    private static final List<ModelElementValidator<?>> VALIDATORS_LIST = CollUtil.newArrayList(
            new EndEventValidator(),
            new UserTaskValidator(),
            new MultiInstanceLoopCharacteristicsValidator(),
            new ExclusiveGatewayValidator()
    );

    public static void validate(BpmnModelInstance bpmnModelInstance) {
        // 校验
        ValidationResults results = bpmnModelInstance.validate(VALIDATORS_LIST);
        if (results.hasErrors()) {
            // 处理错误信息
            StringBuilder msg = new StringBuilder();
            Map<ModelElementInstance, List<ValidationResult>> map = results.getResults();
            Set<Map.Entry<ModelElementInstance, List<ValidationResult>>> entries = map.entrySet();
            for (Map.Entry<ModelElementInstance, List<ValidationResult>> entry : entries) {
                ModelElementInstance key = entry.getKey();
                List<ValidationResult> validationResults = map.get(key);
                for (ValidationResult validationResult : validationResults) {
                    msg.append(validationResult.getMessage()).append("；");
                }
            }
            throw new FlowModelException(msg.toString());
        }
    }
}
